import { login, getInfo, updateUser } from '@/api/login'
import { setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: '',
    username: '',
    avatar: '',
    roles: '',
    intro: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INTRO: (state, intro) => {
      state.intro = intro
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {

      return new Promise((resolve, reject) => {
        login(userInfo.email, userInfo.password).then(response => {
          const data = response.data

          setToken(data.token)

          commit('SET_TOKEN', data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    updateInfo({ commit }, roles) {
      return new Promise((resolve) => {

        updateUser(roles).then(() => {
          commit('SET_USERNAME', roles.username)
          commit('SET_AVATAR', roles.avatar)
          commit('SET_ROLES', roles)
          commit("SET_INTRO", roles.intro)
        })

        resolve()

      })
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          const data = response.data
          commit('SET_USERNAME', data.user.username)
          commit('SET_AVATAR', data.user.avatar)
          commit('SET_ROLES', data.user)
          commit("SET_INTRO", data.user.intro)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    Logout({ commit }) {
      return new Promise((resolve) => {
        commit("SET_USERNAME", '')
        commit("SET_AVATAR", '')
        commit("SET_ROLES", '')
        commit("SET_TOKEN", '')
        commit("SET_INTRO", '')
        removeToken()
        resolve()
      })
    }

  }
}

export default user